﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CueMounter.DokanStructure;

namespace CueMounter {
	public class DokanWaveProviderDirectory : DokanDirectory {
		private DokanFile waveFile;
		private DokanReadOnlyTextFile tagsFile;
		private DokanFile[] files;

		public DokanWaveProviderDirectory(string name, IWaveProvider waveProvider) {
			Name = name;
			var file = new DokanBinaryReadFile(GetMediaFileName(waveProvider.Tags) + ".wav", new WaveFile(waveProvider));
			waveFile = new DokanCachedReadFile(file, 1 * 1024 * 1024);
			tagsFile = new DokanReadOnlyTextFile("Info.txt", GetTagsString(waveProvider.Tags));
			files = new DokanFile[] { waveFile, tagsFile };
		}

		public override void Dispose() {
			waveFile.Dispose();
		}

		private void AppendIfGood(StringBuilder target, string name, string value) {
			if(!string.IsNullOrWhiteSpace(value)) {
				target.AppendLine(name + ": " + value);
			}
		}
		private void AppendIfGood(StringBuilder target, string name, uint value) {
			if(value != 0) {
				target.AppendLine(name + ": " + value);
			}
		}

		private string GetTagsString(TagLib.Tag tags) {
			StringBuilder result = new StringBuilder();
			AppendIfGood(result, "Artist", tags.JoinedPerformers);
			AppendIfGood(result, "Album Artist", tags.JoinedAlbumArtists);
			AppendIfGood(result, "Title", tags.Title);
			AppendIfGood(result, "Track", tags.Track);
			AppendIfGood(result, "Year", tags.Year);
			AppendIfGood(result, "Genre", tags.JoinedGenres);
			AppendIfGood(result, "Disc", tags.Disc);
			AppendIfGood(result, "Disc Count", tags.DiscCount);
			return result.ToString();
		}

		private string GetMediaFileName(TagLib.Tag tag) {
			string performers = tag.JoinedPerformers;
			string title = tag.Title;
			return
				(string.IsNullOrWhiteSpace(performers) ? "Unknown Artist" : performers) +
				" - " +
				(string.IsNullOrWhiteSpace(title) ? "Unknown Title" : title);
		}

		public override DokanFile[] Files {
			get {
				return files;
			}
		}
	}
}
